package distributed.lock.redis;

import distributed.lock.utils.JedisTool;
import utils.Lists;
import java.util.concurrent.TimeUnit;

/**
 * JedisClient 手工实现
 */
public class JedisClientRedisHandle implements RedisHandle {

    @Override
    public boolean setnx(String key, String value, long time, TimeUnit timeUnit) {
        //成功返回OK
        String setnx = JedisTool.setnx(key, value, time, timeUnit);
        return "OK".equals(setnx);
    }

    @Override
    public boolean comparAndDel(String key, String value) {
        String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then \n" +
                "\treturn redis.call('del', KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end\n";

        //删除成功 返回1 否则 返回0
        Object delifequals = JedisTool.delifequals(lua, Lists.of(key), Lists.of(value));
        return delifequals != null && "1".equals(delifequals.toString());
    }
}
